<template>
	<view class="adup-route-bz">
		<u-form :model="fm.ps" :ref="fm.fname" :rules="fm.rules" :error-type="['toast']">
			<view class="my-fm" :style="{'padding-top': '0rpx'}">
				<view class="f-item no-box" :style="{'padding-top': '85rpx'}">
					<view class="f-item-title" :style="{'position': 'fixed', 'top': '-4rpx', 'width': 'calc(100% - 50rpx)', 'padding-left': '20rpx'}">
						<label class="r-l-icon" :style="{'background': '#ff6300', 'left': '0rpx'}"></label>
						行程师傅开支（元）
						<view class="r-r-con">
							<u-button 
								:ripple="true" 
								:hover-class="'none'" 
								:custom-style="fm.sb.okBtnSty" 
								:loading="fm.sb.load"
								@click="submitFm">
								<u-icon name="edit-pen-fill" color="#fff"></u-icon>提交
							</u-button>
							
							<u-button
								:hover-class="'none'" 
								:custom-style="fm.sb.cancleBtnSy" 
								@click="closeMd">
								<u-icon name="arrow-leftward" color="#ff6300"></u-icon>返回
							</u-button>
						</view>
					</view>
					
					<u-form-item prop="singleFee">
						<view class="i-row">
							<view class="r-title">打单费</view>
							<view class="r-con">
								<u-input 
									v-model="fm.ps.singleFee" 
									:type="'digit'" 
									:input-align="'right'"
									:clearable="false"
									:custom-style="{'color': '#00C3CE'}"
									placeholder="请填写打单费（选填）"
								/><label class="i-r-text">元</label>
							</view>
						</view>
					</u-form-item>
					
					<u-form-item prop="washingFee">
						<view class="i-row">
							<view class="r-title">洗车费</view>
							<view class="r-con">
								<u-input 
									v-model="fm.ps.washingFee" 
									:type="'digit'" 
									:input-align="'right'"
									:clearable="false"
									:custom-style="{'color': '#00C3CE'}"
									:placeholder="'请输入洗车费（选填）'"
								/><label class="i-r-text">元</label>
							</view>
						</view>
					</u-form-item>
					
					<u-form-item prop="parkingFeeList">
						<view class="i-collspan-row">
							<view class="icr-title">
								停车费
								<label class="icr-text" :style="{'right': '-30rpx'}">{{fm.ps.parkingFeeList.length}}条记录，共{{allParkingFee}}元</label>
							</view>
							<view class="icr-ul">
								<view 
									class="icr-li"
									v-for="(it, index) in fm.ps.parkingFeeList"
									:key="index">
									<view 
										class="li-left-item" 
										@click="setMpMd({show: true, name: 'parkingFeeList', nameIndex: index})">
										<label class="li-title-icon">
											<u-icon name="map-fill" color="#2979ff" size="40"></u-icon>
										</label>
										<view class="li-con">
											<view class="li-c-text">
												<label class="c-qgreen" v-if="it.address">{{it.address.split(' ')[1]}}</label>
												<label :style="{'color': '#bbb'}" v-else>请选择停车地点</label>
											</view>
											<u-icon
												class="li-cr-icon" 
												:name="'arrow-down-fill'" 
												:color="'#bbb'"
												@click="addParkingFee(index)"
											></u-icon>
										</view>
									</view>
									
									<view class="li-right-item" :style="{'width': index == 0 ? '235rpx' : '175rpx'}">
										<label class="li-title-icon">
											<u-icon name="rmb-circle-fill" color="#ff9900" size="40"></u-icon>
										</label>
										<view class="li-con">
											<!-- <u-input
												v-model="it.money"
												:type="'digit'" 
												:input-align="'left'"
												:clearable="false"
												:maxlength="5"
												:custom-style="inpBtnStyl"
												:placeholder="'金额'"
											/><label class="li-cr-text">元</label> -->
											
											<input
												class="li-inp"
												v-model="it.money"
												:type="'digit'" 
												:maxlength="5"
												:placeholder="'金额'"
											/><label class="li-cr-text">元</label>
										</view>
									</view>
									
									<u-icon
										v-if="index == 0"
										class="li-r-icon" 
										:name="'plus-circle-fill'" 
										:color="'#19be6b'"
										:size="40"
										@click="adupParkingFee(1, index)"
									></u-icon>
									<template v-else>
										<u-icon
											class="li-r-icon" 
											:name="'plus-circle-fill'" 
											:color="'#19be6b'"
											:size="40"
											@click="adupParkingFee(1, index)"
										></u-icon>
										<u-icon
											:style="{'margin-left': '20rpx'}"
											class="li-r-icon" 
											:name="'close-circle-fill'" 
											:color="'#fa3534'"
											:size="40"
											@click="adupParkingFee(0, index)"
										></u-icon>
									</template>
								</view>
							</view>
						</view>
					</u-form-item>
					
					<u-form-item prop="roadFee">
						<view class="i-row">
							<view class="r-title">过路费</view>
							<view class="r-con">
								<u-input 
									v-model="fm.ps.roadFee" 
									:type="'digit'" 
									:input-align="'right'"
									:clearable="false"
									:custom-style="{'color': '#00C3CE'}"
									:placeholder="'请输入过路费（选填）'"
								/><label class="i-r-text">元</label>
							</view>
						</view>
					</u-form-item>
					
					<u-form-item prop="livingFee">
						<view class="i-row">
							<view class="r-title">用餐费</view>
							<view class="r-con">
								<u-input 
									v-model="fm.ps.livingFee" 
									:type="'digit'" 
									:input-align="'right'"
									:clearable="false"
									:custom-style="{'color': '#00C3CE'}"
									:placeholder="'请输入用餐费（选填）'"
								/><label class="i-r-text">元</label>
							</view>
						</view>
					</u-form-item>
					
					<u-form-item prop="waterFee">
						<view class="i-row">
							<view class="r-title">买水费</view>
							<view class="r-con">
								<u-input 
									v-model="fm.ps.waterFee" 
									:type="'digit'" 
									:input-align="'right'"
									:clearable="false"
									:custom-style="{'color': '#00C3CE'}"
									:placeholder="'请输入买水费（选填）'"
								/><label class="i-r-text">元</label>
							</view>
						</view>
					</u-form-item>
					
					<u-form-item prop="stayFee">
						<view class="i-row">
							<view class="r-title">住宿费</view>
							<view class="r-con">
								<u-input 
									v-model="fm.ps.stayFee" 
									:type="'digit'" 
									:input-align="'right'"
									:clearable="false"
									:custom-style="{'color': '#00C3CE'}"
									:placeholder="'请输入住宿费（选填）'"
								/><label class="i-r-text">元</label>
							</view>
						</view>
					</u-form-item>
					
					<u-form-item prop="otherFee">
						<view class="i-row">
							<view class="r-title">其他费</view>
							<view class="r-con">
								<u-input 
									v-model="fm.ps.otherFee" 
									:type="'digit'" 
									:input-align="'right'"
									:clearable="false"
									:custom-style="{'color': '#00C3CE'}"
									:placeholder="'请输入其他费（选填）'"
								/><label class="i-r-text">元</label>
							</view>
						</view>
					</u-form-item>
					
					<u-form-item prop="remark">
						<view class="i-row-textarea">
							<view class="r-title">备注</view>
							<view class="r-con">
								<u-input
									v-model="fm.ps.remark" 
									:type="'textarea'" 
									:custom-style="{'color': '#00C3CE'}"
									:clearable="false"
									:auto-height="true"
									:height="150"
									:maxlength="1000"
									:cursor-spacing="100"
									:placeholder="'请填写您的备注，最多输入1000个字（选填）'"
								/>
							</view>
						</view>
					</u-form-item>
					
					<u-form-item prop="fids" :border-bottom="false">
						<view class="i-row-textarea">
							<view class="r-title">清单凭证<label class="r-title-tip">（最多上传6张图片）</label></view>
							<view class="r-con">
								<u-upload 
									:ref="fm.ufile.ref"
									width="200" 
									height="200" 
									max-count="6"
									:show-progress="false"
									:file-list="fm.ufile.flist"
									:action="fm.ufile.action"
									:header="fm.ufile.header"
									:name="'files'"
									:form-data="fm.ufile.data"
									:max-size="1024*1024*30"
									@on-remove="removeUpFile"
									@on-uploaded="upFileFinish"
								></u-upload>
							</view>
						</view>
					</u-form-item>
					
				</view>
			</view>
		</u-form>
		
		<MapSearchList v-if="mpMd.show" :name="mpMd.name" :nameIndex="mpMd.nameIndex" @myClick="setMpMd"></MapSearchList>
	</view>
</template>

<script>
	import MapSearchList from '@/components/map-search-list/map-search-list.vue';
	
	export default {
		name:"adup-route-bz",
		components: { MapSearchList },
		props: {
			// 父级传入数据
			myData: {
				type: Object
			},
		},
		data() {
			return {
				// 维修详情输入框样式
				inpBtnStyl: {'color': '#00C3CE', 'padding-right': '30rpx'},
				
				// 关联订单对象
				order: null,
				// 表单对象
				fm: {
					fname: 'routeBzFm',
					sb: {
						load: false,
						text: '添加', 
						okBtnSty: {
							'background-color': '#00C3CE', 
							'color': '#FFFFFF', 
							'margin-left': '10rpx', 
							'height': '66rpx', 
							'font-size': '30rpx', 
							'padding': '0 20rpx',
						},
						cancleBtnSy: {
							'color': '#ff6300', 
							'margin-left': '10rpx', 
							'height': '66rpx', 
							'font-size': '30rpx', 
							'padding': '0 20rpx',
						}
					},
					// 参数对象
					ps: {
						// 修改对象id
						uid : '',
						// 订单编号
						orderNum: '',
						// 打单费
						singleFee: '',
						// 洗车费
						washingFee: '',
						// 停车费详情
						parkingFeeList: [
							{
								// 地址 eg：成都市 天府广场
								address: '', 
								// 坐标 eg：104.xxxxxx,30.xxxxxx
								lnglat: '', 
								// 金额 eg：30
								money: '',
							}
						],
						// 过路费
						roadFee: '',
						// 过路费类型 0-现金 1-ETC
						roadFeeType: 0,
						// 用餐费
						livingFee: '',
						// 其他费
						otherFee: '',
						// 买水费
						waterFee: '',
						// 住宿费
						stayFee: '',
						// 备注
						remark: '',
						// 图片id数组 
						fids: []
					},
					// 图片上传对象
					ufile: {
						ref: 'myUpfile',
						// 请求地址
						action: this.C.upfileUrl,
						// 请求头信息
						header: {'X-Token': uni.getStorageSync(this.C.uuid)},
						// 上传携带的参数
						data: {
							// 报账类型
							ftype: 'XCSZ_IMG',
							// 订单编号
							orderNum: '',
							// 行程报账修改id
							uid: '',
						},
						// 文件列表
						flist: [],
					},
					// 验证对象
					rules: {
						// 图片验证
						fids: [
							{
								validator: (rule, value, callback) => {
									if(value.length == 0){
										return false;
									}else{
										return true;
									}
								},
								message: '至少需要上传一张费用清单图片', 
								trigger: ['change']
							}
						]
					},
				},
				
				// 地图弹框
				mpMd: {show: false, name: '', nameIndex: ''}
			}
		},
		watch: {
			myData: {
				handler(o){
					console.log('监听父级传入订单数据', o);
					
					if(o){
						this.order = o;
						
						// 设置表单参数
						this.fm.ps.orderNum = o.orderNum;
						// 设置上传图片额外携带参数
						this.fm.ufile.data.orderNum = o.orderNum;
						
						// 初始化-订单报账记录
						this.getOrderRouteBz(o.orderNum);
					}
				},
				// 深度监听（属性修改也执行）
				deep: true,
				// 第一次就监听
				immediate: true
			},
		},
		computed: {
			// 行程收支停车费总金额
			allParkingFee: function(){
				let total = 0;
				if(this.fm && this.fm.ps.parkingFeeList){
					this.fm.ps.parkingFeeList.forEach(it => { total += Number(it.money); });
				}
				return total;
			}
		},
		mounted() {
			const that = this, fm = that.fm;
			
			// 绑定表单验证规则
			fm.sb.load = true;
			that.$nextTick(function(){
				fm.sb.load = false; 
				
				// 绑定表单验证规则
				that.$refs[that.fm.fname].setRules(that.fm.rules);
				
				// 先赋值，再清空（防止第一次placeholder不生效问题）
				if(!fm.ps.uid){// 添加需要
					fm.ps.remark = ' ';
					setTimeout(() => { fm.ps.remark = ''; }, 1000);
				}
			});
		},
		created(){
			const that = this, fm = that.fm, order = that.order;
			
			console.log('父级传入数据', that.myData);
			
		},
		methods: {
			// 关闭弹框
			closeMd(){
				this.$emit('myClick', {show: false});
			},
			// 重置表单
			resetForm(){
				let that = this, fm = that.fm;
				console.log('重置表单');
				// 清空一下之前文件列表
				that.$refs[fm.ufile.ref].clear();
				fm.ufile.flist = [];
				
				fm.ps = {
					// 修改对象id
					uid : '',
					// 订单编号
					orderNum: '',
					// 打单费
					singleFee: '',
					// 洗车费
					washingFee: '',
					// 停车费详情
					parkingFeeList: [{address: '', lnglat: '', money: ''}],
					// 过路费
					roadFee: '',
					// 过路费类型 0-现金 1-ETC
					roadFeeType: 0,
					// 用餐费
					livingFee: '',
					// 其他费
					otherFee: '',
					// 买水费
					waterFee: '',
					// 住宿费
					stayFee: '',
					// 备注（这里要设置成空）
					remark: ' ',
					// 图片id数组 
					fids: []
				};
				
				// 重新设置备注
				setTimeout(() => { fm.ps.remark = ''; }, 1000);
			},
			// 获取-订单的报账记录
			getOrderRouteBz(orderNum){
				let that = this, U = that.U, fm = that.fm;
				
				that.$u.api.getOrderOfRouteBz({orderNum: orderNum}).then(res => {
					if(res.code != 1 || (res.code == 1 && !res.data)){
						that.resetForm();// 清空表单数据
					}else{
						// console.log('订单报账记录', res.data);
						
						// console.log('当前表单', fm.ps);
						
						let o = res.data;
						if(o){
							// 设置上传图片额外携带参数
							this.fm.ufile.data.uid = o.id;
							
							let p = {};
							// 修改对象id
							p.uid = o.id;
							// 订单编号
							p.orderNum = o.orderNum;
							// 打单费
							p.singleFee = o.singleFee == 0 ? '' : o.singleFee;
							// 洗车费
							p.washingFee = o.washingFee == 0 ? '' : o.washingFee;
							
							// 停车费用详情
							let pklist = o.parkingFeeDetail;
							if(pklist.length > 0){// 有停车费
								p.parkingFeeList = [];
								pklist.forEach(it => {
									p.parkingFeeList.push({address: it.position, lnglat: it.lngLat, money: it.parkingFee+''});
								});
							}else{
								p.parkingFeeList = [{address: '', lnglat: '', money: ''}];
							}
							
							// 过路费
							p.roadFee = o.roadFee == 0 ? '' : o.roadFee;
							// 过路费类型 0-现金 1-ETC
							p.roadFeeType = 0,
							// 用餐费
							p.livingFee = o.livingFee == 0 ? '' : o.livingFee;
							// 其他费
							p.otherFee = o.otherFee == 0 ? '' : o.otherFee;
							// 买水费
							p.waterFee = o.waterFee == 0 ? '' : o.waterFee;
							// 住宿费
							p.stayFee = o.stayFee == 0 ? '' : o.stayFee;
							// 备注（此处如果备注为空，则设置一个长度的空字符）
							p.remark = o.remark == '' ? ' ' : o.remark;
							
							// console.log('传入的图片地址', o.routeVoucherUrl);
							
							// 清空一下之前文件列表
							that.$refs[fm.ufile.ref].clear();
							// 处理图片数据
							if(o.routeVoucherUrl.length > 0){
								let fidArr = [], flist = [];
								
								o.routeVoucherUrl.forEach(it => {
									if(it.key && it.key != 'null'){
										let is = fidArr.findIndex(a => a == it.key);
										if(is == -1){// 去重
											fidArr.push(it.key);
											flist.push({
												id: it.key,
												url: that.C.imgUrl+it.val
											});
										}
									}
								});
								
								// 图片ids
								p.fids = fidArr;
								// 设置图片默认显示数据
								fm.ufile.flist = flist;
							}else{
								p.fids = [];
								// 置空
								fm.ufile.flist = [];
							}
							// 赋值表单数据
							fm.ps = p;
							
							console.log('赋值后的表单数据', fm.ps);
						}
					}
				});
			},
			// 删除图片
			removeUpFile(index, lists, name){
				let fids = this.fm.ps.fids;
				
				fids.splice(index, 1);
				
				// console.log('删除后的文件id', this.fm.ps.fids);
			},
			// 所有图片上传完成
			upFileFinish(lists, name){
				let fids = this.fm.ps.fids;
				// console.log('上传图片的参数', this.fm.ufile.data);
				
				lists.forEach(it => {
					if(it.response) {
						let id = it.response.data[0];
						let is = fids.findIndex(a => a == id);
						if(is == -1) fids.push(id);
					}
				});
				
				// console.log('文件列表', lists);
				// console.log('图片id数组', this.fm.ps.fids);
			},
			// 打开地图地址选择列表
			setMpMd(e){
				const that = this, U = that.U, md = that.mpMd, ps = that.fm.ps;
				
				if(e.show){
					// 准备数据
					md.name = e.name;
					md.nameIndex = e.nameIndex;
				}else{
					console.log('子组件传入的数据', e);
					if(e.obj){// 存在地点数据对象、
						ps[e.name][e.nameIndex].address = `${e.obj.area.split('-')[1]} ${e.obj.name}`;
						ps[e.name][e.nameIndex].lnglat = e.obj.lnglat;
					}
				}
				
				md.show = e.show;
			},
			/**
			 * 添加/删除-停车费详情
			 * @param {Object} type 操作类型 1-添加 0-删除
			 * @param {Object} index 下标
			 */
			adupParkingFee(type, index){
				let that = this, U = that.U, pklist = U.scopy(that.fm.ps.parkingFeeList);
				console.log('传入的值', type, index);
				if(type == 0){
					U.qconfim('确定删除吗？', function(e){
						if(e.confirm) {
							pklist.splice(index, 1);
							that.fm.ps.parkingFeeList = pklist;
						}
					});
				}else{
					let arr = [];
					pklist.forEach((it, i) => {
						arr.push(it);
						if(i == index) arr.push({address: '', lnglat: '', money: ''});
					});
					that.fm.ps.parkingFeeList = arr;
					
					console.log('新增的结果', that.fm.ps.parkingFeeList);
				}
			},
			// 表单提交
			submitFm(){
				let that = this, U = that.U, FV = that.FV, fm = that.fm, ps = U.scopy(fm.ps), sb = fm.sb;
				console.log(ps);
				that.$refs[fm.fname].validate((valid) => {
					if (!valid) { return false; } else {
						// 参数处理
						let fg = true;
						
						if(fg){
							ps.orderNum = that.order.orderNum;
							if(!ps.orderNum){
								fg = U.qinfo('请选择一条行程订单');
							}
						}
						
						// 处理停车费详情
						if(fg){
							let parkingFeeList = ps.parkingFeeList, parkingFeeArr = [];
							for(let i = 0; i < parkingFeeList.length; i++){
								let it = parkingFeeList[i];
								
								if(it.address && !it.money){
									fg = U.qinfo('请填写第'+(i+1)+'项停车位置');
									break;
								}else if(!it.address && it.money){
									fg = U.qinfo('请填写第'+(i+1)+'项停车费用');
									break;
								}else if(!it.address && !it.money){
									// 记录不止一条才验证
									if(parkingFeeList.length != 1){
										fg = U.qinfo('请将第'+(i+1)+'项停车详情补充完整');
										break;
									}
								}else if(!FV.isFloat(it.money)){
									fg = U.qinfo('第'+(i+1)+'项停车费用格式错误');
									break;
								}else{
									// 地址=坐标=金额
									parkingFeeArr.push(it.address+'='+it.lnglat+'='+it.money);
								}
							}
							
							if(parkingFeeArr.length > 0) ps.parkingFees = parkingFeeArr.join(';');
						}
						
						if(fg){
							if(ps.fids.length == 0){
								fg = U.qinfo('至少需要上传一张费用清单图片');
							}else{
								ps.fids = ps.fids.join(',');
							}
						}
						
						if(fg){
							sb.load = true;
							that.$u.api.adupOrderRouteBz(ps).then((res) => {
								sb.load = false;
							
								if(res.code == 1){
									U.qinfo(res.msg, 1000);
								  
									// 赋值报账记录id，方便修改
									fm.ps.uid = res.uid;
									// 设置-上传文件提交参数
									fm.ufile.data.uid = res.uid;
									
									that.$emit('myClick', {show: false});
								}else{
									U.qerror(res.msg);
								}
							}).catch(err => { sb.load = false;});
						}
					}
				});
			}
			
		}
	}
</script>

<style>

</style>
